Popular Searches
Popular Course Categories
Popular Courses

Embedding Expressions in JSX

Embedding Expressions in JSX

JSX in React

Embedding Expressions in JSX – Detailed Notes

Embedding Expressions in JSX is an important concept in React that allows developers to insert JavaScript expressions inside JSX markup using curly braces {}. It helps display dynamic content, calculate values, access object properties, call functions, render lists, apply styles, and create interactive user interfaces.

For example, instead of writing a fixed name inside a heading, you can use a JavaScript variable to display a name dynamically.

function App() {
  const name = "Rahul";
  return <h1>Hello, {name}!</h1>;
}
export default App;

Output: Hello, Rahul!

Official Documentation: JavaScript in JSX with Curly Braces


1. What Does Embedding Expressions in JSX Mean?

Embedding expressions in JSX means placing a valid JavaScript expression inside JSX markup using curly braces. React evaluates the expression and uses its result when rendering the interface.

A JavaScript expression is code that produces a value, such as a string, number, calculation result, variable value, function return value, or conditional expression.

Example

function App() {
  const course = "React JS";
  const price = 5000;
  return (
    <div>
      <h1>{course}</h1>
      <p>Course Price: ₹{price}</p>
      <p>Total: {price + 1000}</p>
    </div>
  );
}
export default App;

Output:

  • React JS
  • Course Price: ₹5000
  • Total: 6000

In this example, JSX reads the values of course and price, and calculates price + 1000.


2. Why Do We Use Expressions in JSX?

Expressions make React interfaces dynamic instead of limiting them to static text and markup.

  • Display dynamic data: Show names, prices, messages, and other variable values.
  • Perform calculations: Calculate totals, discounts, scores, and other values.
  • Access object properties: Display information stored in JavaScript objects.
  • Call functions: Display the result returned by a function.
  • Render lists: Convert arrays into JSX elements.
  • Apply conditional rendering: Display different content depending on a condition.
  • Set dynamic attributes: Change image sources, alternative text, class names, and other properties.
  • Apply dynamic styling: Set styles using JavaScript objects.

3. Understanding Curly Braces in JSX

Curly braces {} create a connection between JSX markup and JavaScript expressions. They can be used in two main places: inside an element's content and inside an attribute value after the equals sign.

A. Inside JSX Content

function App() {
  const name = "Priya";
  return <h1>Welcome, {name}!</h1>;
}
export default App;

Here, {name} inserts the value of the variable into the heading.

B. Inside JSX Attributes

function App() {
  const imageUrl = "/images/profile.png";
  const imageAlt = "User profile";
  return <img src={imageUrl} alt={imageAlt} />;
}
export default App;

Here, src={imageUrl} and alt={imageAlt} use JavaScript variables as attribute values.

Important: Use quotes for literal string values, such as alt="User profile", and curly braces for JavaScript expressions, such as alt={imageAlt}.


4. Embedding Variables in JSX

Variables store values that can be displayed in JSX. This makes it easy to update content by changing the data rather than rewriting the markup.

Example

function App() {
  const studentName = "Amit";
  const courseName = "React JS";
  const duration = "3 Months";
  return (
    <div>
      <h1>Student Details</h1>
      <p>Name: {studentName}</p>
      <p>Course: {courseName}</p>
      <p>Duration: {duration}</p>
    </div>
  );
}
export default App;

Output:

  • Student Details
  • Name: Amit
  • Course: React JS
  • Duration: 3 Months

Explanation: The variables are declared inside the component, and their values are inserted into the JSX using curly braces.


5. Embedding Mathematical Expressions in JSX

JavaScript calculations can be performed directly inside JSX. This is useful for displaying totals, percentages, prices, and other calculated values.

Example 1: Addition

function App() {
  return <p>Total: {10 + 20}</p>;
}
export default App;

Output: Total: 30

Example 2: Multiplication

function App() {
  const quantity = 3;
  const price = 500;
  return <p>Total Price: ₹{quantity * price}</p>;
}
export default App;

Output: Total Price: ₹1500

Example 3: Percentage Calculation

function App() {
  const marks = 450;
  const totalMarks = 500;
  const percentage = (marks / totalMarks) * 100;
  return <p>Percentage: {percentage}%</p>;
}
export default App;

Output: Percentage: 90%

Common Mathematical Operators

Operator Meaning Example Result
+ Addition {5 + 3} 8
- Subtraction {10 - 4} 6
* Multiplication {4 * 5} 20
/ Division {20 / 4} 5
% Remainder {10 % 3} 1
** Exponentiation {2 ** 3} 8

6. Embedding String Expressions in JSX

String expressions allow you to combine text, variables, and other string values in JSX.

Example 1: String Concatenation

function App() {
  const firstName = "Rahul";
  const lastName = "Sharma";
  return <h2>{firstName + " " + lastName}</h2>;
}
export default App;

Output: Rahul Sharma

Example 2: Template Literals

function App() {
  const name = "Priya";
  const course = "React JS";
  return <p>{`${name} is learning ${course}.`}</p>;
}
export default App;

Output: Priya is learning React JS.

Template literals use backticks and allow JavaScript values to be embedded with ${...}.

Example 3: Convert Text to Uppercase

function App() {
  const course = "react js";
  return <h2>{course.toUpperCase()}</h2>;
}
export default App;

Output: REACT JS


7. Embedding Object Properties in JSX

JavaScript objects store related information as key-value pairs. You can access individual properties with dot notation or bracket notation and display their values in JSX.

Example

function App() {
  const student = {
    name: "Neha",
    age: 22,
    course: "React JS"
  };
  return (
    <div>
      <h2>{student.name}</h2>
      <p>Age: {student.age}</p>
      <p>Course: {student.course}</p>
    </div>
  );
}
export default App;

Output: Neha, Age: 22, Course: React JS.

Using Bracket Notation

function App() {
  const student = {
    name: "Neha",
    course: "React JS"
  };
  const property = "course";
  return <p>{student[property]}</p>;
}
export default App;

Output: React JS

Important: You generally cannot render an ordinary JavaScript object directly as a child, for example {student}. Instead, display a property such as {student.name}, or convert suitable data into a displayable string.


8. Embedding Function Calls in JSX

You can call a JavaScript function inside JSX when the function returns a value that can be rendered.

Example 1: Simple Function

function getMessage() {
  return "Welcome to React!";
}
function App() {
  return <h2>{getMessage()}</h2>;
}
export default App;

Output: Welcome to React!

Example 2: Function with Parameters

function greetUser(name) {
  return `Hello, ${name}!`;
}
function App() {
  return <h2>{greetUser("Amit")}</h2>;
}
export default App;

Output: Hello, Amit!

Example 3: Calculate a Discount

function calculateDiscount(price, discount) {
  return price - (price * discount / 100);
}
function App() {
  return <p>Final Price: ₹{calculateDiscount(1000, 10)}</p>;
}
export default App;

Output: Final Price: ₹900

Best Practice: Functions used while rendering should generally be pure and predictable. Avoid performing side effects, such as changing external data or making network requests, during rendering.


9. Embedding Conditional Expressions in JSX

Conditional expressions allow you to display different content depending on a condition. The most common approaches are the ternary operator and logical AND operator.

Example 1: Ternary Operator

function App() {
  const isLoggedIn = true;
  return (
    <div>
      {isLoggedIn
        ? <h2>Welcome Back!</h2>
        : <h2>Please Log In</h2>}
    </div>
  );
}
export default App;

Output: Welcome Back!

Example 2: Logical AND Operator

function App() {
  const hasNotification = true;
  return (
    <div>
      {hasNotification && <p>You have a new notification.</p>}
    </div>
  );
}
export default App;

Output: You have a new notification.

Example 3: Display a Message Based on Marks

function App() {
  const marks = 75;
  return (
    <div>
      <p>Marks: {marks}</p>
      <p>{marks >= 40 ? "Pass" : "Fail"}</p>
    </div>
  );
}
export default App;

Output: Marks: 75, Pass.

Important: When using &&, avoid placing a number directly on the left if it could be zero. For example, {0 &&

Hello

} displays 0. Use a boolean comparison such as count > 0 && ....


10. Embedding Array Expressions and Rendering Lists

Arrays can be processed using methods such as map() to generate JSX elements. This is useful for displaying products, students, courses, notifications, and other collections of data.

Example

function App() {
  const courses = ["HTML", "CSS", "JavaScript", "React JS"];
  return (
    <div>
      <h2>Available Courses</h2>
      <ul>
        {courses.map((course) => (
          <li key={course}>{course}</li>
        ))}
      </ul>
    </div>
  );
}
export default App;

Explanation:

  • courses contains an array of course names.
  • map() processes each array item.
  • is generated for each course.
  • key={course} gives each item a stable key in this example because the names are unique.

When rendering data from a database or API, prefer a stable unique identifier such as course.id for the key.


11. Embedding Expressions in JSX Attributes

Expressions can be used in attributes to make elements dynamic. This is particularly useful for images, links, CSS classes, accessibility attributes, and custom component props.

Example 1: Dynamic Image

function App() {
  const imageUrl = "/images/student.png";
  const imageDescription = "Student profile";
  return (
    <img src={imageUrl} alt={imageDescription} />
  );
}
export default App;

Example 2: Dynamic Link

function App() {
  const courseUrl = "https://react.dev/";
  return (
    <a href={courseUrl}>Learn React</a>
  );
}
export default App;

Example 3: Dynamic Class Name

function App() {
  const isActive = true;
  return (
    <button className={isActive ? "active" : "inactive"}>
      Continue
    </button>
  );
}
export default App;

The value of className depends on the value of isActive.


12. Embedding JavaScript Objects for Inline Styling

JSX supports inline styling through a JavaScript object passed to the style property. This is why you may see two pairs of curly braces in a JSX style attribute.

Example

function App() {
  return (
    <h1 style={{ color: "blue", fontSize: "32px" }}>
      Welcome to React
    </h1>
  );
}
export default App;

Understanding the Double Curly Braces:

  • The outer braces {} tell JSX that a JavaScript expression follows.
  • The inner braces {} define a JavaScript object.
  • color and fontSize are properties of that object.

Using a Separate Style Object

function App() {
  const headingStyle = {
    color: "blue",
    backgroundColor: "lightgray",
    padding: "12px"
  };
  return <h1 style={headingStyle}>React Training</h1>;
}
export default App;

CSS properties in style objects generally use camelCase, such as backgroundColor instead of background-color.


13. Embedding Expressions with Props in React Components

Props allow a parent component to pass data to a child component. JSX expressions can supply dynamic values to these props.

Example

function Student({ name, course }) {
  return (
    <div>
      <h2>{name}</h2>
      <p>Course: {course}</p>
    </div>
  );
}
function App() {
  const studentName = "Neha";
  const selectedCourse = "React JS";
  return (
    <Student name={studentName} course={selectedCourse} />
  );
}
export default App;

Explanation:

  • App defines two variables.
  • The variables are passed to Student as props.
  • The child component displays the values through JSX expressions.

This approach makes components reusable because the same Student component can display different data.


14. Expressions vs. Statements in JSX

A JavaScript expression produces a value. A statement performs an action or controls program flow. JSX curly braces accept expressions, not standalone statements.

Code Type Can Be Used Directly Inside JSX Braces?
2 + 3 Expression Yes
student.name Expression Yes
getMessage() Function-call expression Yes, if its result is suitable for rendering
isLoggedIn ? "Yes" : "No" Conditional expression Yes
items.map(item => ...) Method-call expression Yes
if (isLoggedIn) { ... } Statement No, not directly
for (const item of items) { ... } Statement No, not directly
const name = "Amit" Variable declaration statement No, declare it before the return instead

Incorrect Example

function App() {
  return <h1>{if (true) "Hello"}</h1>;
}

Correct Example Using a Ternary Expression

function App() {
  const isVisible = true;
  return <h1>{isVisible ? "Hello" : "Goodbye"}</h1>;
}
export default App;

Correct Example Using an if Statement Before return

function App() {
  const isVisible = true;
  let message = "Goodbye";
  if (isVisible) {
    message = "Hello";
  }
  return <h1>{message}</h1>;
}
export default App;

15. What Values Can JSX Render?

JSX can render many types of values, but not all JavaScript values are displayed as visible text.

Value Type Example Typical Result
String {"Hello"} Displays Hello.
Number {100} Displays 100.
Calculation {10 + 5} Displays 15.
Boolean {true} Displays no text by itself.
null {null} Displays no content.
undefined {undefined} Displays no content.
Array {["A", "B"]} Can render its renderable items in sequence.
Plain object {{ name: "Amit" }} Cannot be rendered directly as a normal React child.
React element {

Hello

}
Renders the element.

Important: A plain object cannot normally be displayed directly as a React child. Access its properties or convert its data into a suitable string or collection of JSX elements.


16. Common Mistakes When Embedding Expressions

Mistake Incorrect Code Correct Approach
Using a variable as literal text

name

{name}

Putting quotes around an expression attribute src="{imageUrl}" src={imageUrl}
Rendering a plain object

{student}

{student.name}

Using an if statement directly inside JSX {if (show) "Hello"} Use a ternary expression or prepare a variable before return.
Displaying zero unintentionally {count &&

Messages

}
{count > 0 &&

Messages

}
Calling a side-effecting function during rendering Calling a function that changes external data inside JSX. Keep rendering pure and handle side effects in appropriate event handlers or Effects.
Missing list keys items.map(item =>
  • {item}
  • )
    Provide a suitable stable key to each list item.

    17. Practical Example: Product Information Card

    This example combines variables, object properties, calculations, function calls, conditional expressions, and inline styling in one React component.

    function ProductCard() {
      const product = {
        name: "Wireless Headphones",
        price: 2000,
        discount: 10,
        inStock: true
      };
    
      function calculatePrice(price, discount) {
        return price - (price * discount / 100);
      }
    
      const finalPrice = calculatePrice(product.price, product.discount);
      const cardStyle = {
        border: "1px solid #ccc",
        padding: "16px",
        borderRadius: "8px",
        maxWidth: "320px"
      };
    
      return (
        <div style={cardStyle}>
          <h2>{product.name}</h2>
          <p>Original Price: ₹{product.price}</p>
          <p>Discount: {product.discount}%</p>
          <p>Final Price: ₹{finalPrice}</p>
          <p>
            {product.inStock ? "Available" : "Out of Stock"}
          </p>
        </div>
      );
    }
    export default ProductCard;

    Concepts Demonstrated

    • Object property expressions: {product.name}.
    • Mathematical calculations through a function call.
    • Variable expressions: {finalPrice}.
    • Conditional rendering using the ternary operator.
    • JavaScript object values for inline styling.

    Practice Tasks

    1. Change the product name and original price.
    2. Set the discount to 20% and check the final price.
    3. Set inStock to false and observe the displayed message.
    4. Add a product category and display it using an object property.
    5. Display multiple products using an array and map().
    6. Add a button with an event handler to show a product message.

    18. Best Practices for Embedding Expressions in JSX

    • Use curly braces when inserting JavaScript expressions into JSX.
    • Use quotes for fixed string attributes and braces for dynamic attribute values.
    • Keep complex calculations outside the JSX markup when that improves readability.
    • Use meaningful variable and function names.
    • Display specific object properties rather than attempting to render plain objects.
    • Use ternary expressions for simple two-way conditional rendering.
    • Use logical AND for conditional content, with care around numeric zero values.
    • Use stable keys when rendering arrays of elements.
    • Avoid side effects during rendering.
    • Use style objects with appropriate camelCase CSS property names.
    • Break large components into smaller reusable components when necessary.
    • Check the browser console and development terminal for errors.

    19. Interview Questions and Answers

    Q1. What does embedding expressions in JSX mean?

    It means using curly braces to insert JavaScript expressions into JSX markup so their values can be displayed or passed as attributes.

    Q2. Why are curly braces used in JSX?

    Curly braces let JSX evaluate JavaScript expressions, including variables, calculations, function calls, object properties, and conditional expressions.

    Q3. Can we use variables inside JSX?

    Yes. For example,

    {name}

    displays the value of the name variable.

    Q4. Can we perform calculations inside JSX?

    Yes. For example,

    {10 + 20}

    displays 30.

    Q5. Can we call a function inside JSX?

    Yes, if the function returns a value suitable for rendering. For example,

    {getMessage()}

    .

    Q6. Can we render a JavaScript object directly?

    Not as an ordinary React child. Instead, render a property such as {student.name} or transform the object into suitable JSX.

    Q7. What is the difference between an expression and a statement?

    An expression produces a value, whereas a statement performs an action or controls program flow. JSX braces accept expressions, not standalone statements such as if and for.

    Q8. Can curly braces be used inside JSX attributes?

    Yes. For example, {description} uses variables for attribute values.

    Q9. Why do inline styles often use double curly braces?

    The outer braces introduce a JavaScript expression, while the inner braces define the JavaScript object containing style properties.

    Q10. How can conditional rendering be performed in JSX?

    Use JavaScript expressions such as the ternary operator or logical AND, or calculate the content in a variable before returning JSX.

    Q11. Can arrays be rendered using JSX expressions?

    Yes. Arrays are commonly processed with map() to generate elements, with an appropriate key for each list item.

    Q12. What happens if a boolean is embedded directly in JSX?

    Boolean values generally do not display visible text by themselves. Use a condition to display a meaningful message when needed.


    20. Quick Revision Checklist

    • Understand what JavaScript expressions are.
    • Know how curly braces work inside JSX.
    • Embed variables and string expressions.
    • Perform mathematical calculations.
    • Access object properties.
    • Call functions that return renderable values.
    • Use ternary and logical AND expressions.
    • Render arrays using map() and stable keys.
    • Use dynamic values in attributes.
    • Understand double curly braces for inline style objects.
    • Recognize the difference between expressions and statements.
    • Avoid rendering plain objects directly as React children.

    21. Conclusion

    Embedding expressions in JSX allows React developers to combine JavaScript data and logic with user interface markup. By using curly braces correctly, you can display dynamic values, calculate results, access object properties, call functions, render lists, apply styles, and show conditional content.

    Practise these concepts with small React components before moving on to more advanced topics such as props, state, Hooks, forms, API integration, and routing.

    Explore React JS Training: JustAcademy React JS Training Course

    Register for a Course Demo: Register for React JS Course Demo

    Official Learning Resource: JavaScript in JSX with Curly Braces – React Documentation

    whatsapp